package com.cnswhy.cloud.server.comsumer.consumer.customer;

import com.cnswhy.cloud.common.core.mybatis.conditions.Wraps;
import com.cnswhy.cloud.server.common.entity.mq.SyncIpMsg;
import com.cnswhy.cloud.server.comsumer.event.SyncLoginIpEvent;
import com.cnswhy.cloud.server.core.channel.aliyun.AliyunIpService;
import com.cnswhy.cloud.server.core.channel.aliyun.dto.IPinfoResponse;
import com.cnswhy.cloud.server.core.channel.aliyun.dto.IpData;
import com.cnswhy.cloud.server.core.entity.CustomerDeviceInfo;
import com.cnswhy.cloud.server.core.service.CustomerDeviceInfoService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 同步登录IP
 */
@Component
@Slf4j
public class SyncLoginIpConsumer implements SyncLoginIpEvent {
    @Autowired
    CustomerDeviceInfoService customerDeviceInfoService;
    @Autowired
    AliyunIpService aliyunIpService;

    @Override
    public void sync(SyncIpMsg syncIpMsg) {
        log.info("登录IP消息：{}", syncIpMsg.toString());
        if(syncIpMsg.getCustomerId() == null){
            return;
        }
        if(StringUtils.isBlank(syncIpMsg.getLoginIp())){
            return;
        }
        CustomerDeviceInfo customerDeviceInfo = customerDeviceInfoService.getOne(Wraps.<CustomerDeviceInfo>lbQ().eq(CustomerDeviceInfo::getCustomerId, syncIpMsg.getCustomerId()));
        if(customerDeviceInfo == null){
            customerDeviceInfo = new CustomerDeviceInfo();
            customerDeviceInfo.setCustomerId(syncIpMsg.getCustomerId());
            customerDeviceInfoService.save(customerDeviceInfo);
        }
        try {
            IPinfoResponse iPinfoResponse = aliyunIpService.getIPinfo(syncIpMsg.getLoginIp());
            if(!"200".equals(iPinfoResponse.getRet())){
                return;
            }
            IpData ipData = iPinfoResponse.getData();
            customerDeviceInfo.setLoginIp(syncIpMsg.getLoginIp());
            customerDeviceInfo.setArea(ipData.getArea());
            customerDeviceInfo.setProv(ipData.getProv());
            customerDeviceInfo.setCity(ipData.getCity());
            customerDeviceInfo.setCountry(ipData.getCountry());
            customerDeviceInfo.setLat(ipData.getLat());
            customerDeviceInfo.setLng(ipData.getLng());
            customerDeviceInfoService.updateById(customerDeviceInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
